package com.lottery.im.module.service.ui;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.bank.UserBankList;
import com.lottery.im.api.result.entity.integral.AccOutCondition;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.ui.NewFragmentActivity;
import com.lottery.im.module.service.presenter.CashExchangePresenter;
import com.lottery.im.module.service.view.CashExchangeView;
import com.lottery.im.util.ToastUtils;
import com.lottery.im.widget.dialog.ConfirmWarnDialogBuilder;
import com.lottery.im.widget.dialog.PassValidationDialogBuilder;

/**
 * 作者：cyy
 * 时间：2018/9/26。
 */
public class CashExchangeFragment
    extends BaseSwipeFragment<CashExchangePresenter>
    implements CashExchangeView, TextWatcher {
  @BindView(R.id.tv_title) TextView tvTitle;
  @BindView(R.id.et_money) EditText etMoney;
  @BindView(R.id.tv_exchangmoney) TextView tvExChangMoney;
  @BindView(R.id.imageView) ImageView imageView;
  @BindView(R.id.bankName) TextView bankName;
  @BindView(R.id.bankDetail) TextView bankDetail;
  @BindView(R.id.linearLayout) LinearLayout linearLayout;

  private float mMoney = 0;

  private UserBankList mUserBankList;

  private final static int REUQESTCODE = 200;
  public final static int RESULTCODE = 500;
  private float maxAmount;
  private float canOutAmount=0f;

  public CashExchangeFragment() {
  }

  @Override protected int getLayoutResId() {
    return R.layout.fragment_cash_exchange;
  }

  @Override protected void initPresenter() {
    presenter = new CashExchangePresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    tvTitle.setText("积分兑换");

    presenter.queryAccOutCondition();

    etMoney.addTextChangedListener(this);
  }

  @OnClick({ R.id.iv_back, R.id.btn_confirm, R.id.container2 })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.container2:
        startFragmentForResult(new BankSelectFragment(), REUQESTCODE);
        break;
      case R.id.btn_confirm:
        if (mMoney <= 0) {
          ToastUtils.showToast(mActivity, "请输入金额");
        } else if (mUserBankList == null) {
          ToastUtils.showToast(mActivity, "请选择银行");
        } else if (!MyApplication.getInstance().getUserInfo().getIsSetPayPwd().equals("Y")) {
          ConfirmWarnDialogBuilder.getInstance(mActivity).setContent("请先设置资金密码")
              .setCancel("取消", null)
              .setConfirm("去设置", v -> NewFragmentActivity.create(mActivity,
                  NewFragmentActivity.FragmentInfoType.SETMONEYPWD)).show();
        } else {
          PassValidationDialogBuilder.getInstance(mActivity).setCallBack(
              code -> presenter.userAccOut(code,
                  mUserBankList.getBankId() + "", mMoney + "")).show();
        }
        break;
    }
  }

  @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  }

  @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  }

  @Override public void afterTextChanged(Editable editable) {
    String inputMoney = etMoney.getText().toString().trim();
    if (!TextUtils.isEmpty(inputMoney) && Integer.valueOf(inputMoney) > canOutAmount) {
      ToastUtils.showToast(mActivity, "输入金额不能大于兑换金额");
      etMoney.setText("");
    } else if (!TextUtils.isEmpty(inputMoney)) {
      Float fInput = Float.valueOf(inputMoney);
      if (maxAmount != 0 && fInput <= maxAmount) {
        mMoney = fInput;
      } else {
        ToastUtils.showToast(mActivity, "输入金额大于最大可兑换金额");
      }
    }
  }

  @Override protected void onFragmentResult(int requestCode, int resultCode, Intent data) {
    super.onFragmentResult(requestCode, resultCode, data);
    if (requestCode == REUQESTCODE && resultCode == BankSelectFragment.RESULTCODE) {
      mUserBankList = (UserBankList) data.getSerializableExtra("userBankList");
      bankName.setText(mUserBankList.getBankName());
      String bankAccount = mUserBankList.getBankAccount();
      bankDetail.setText("储蓄卡尾号为"
          + bankAccount.substring(bankAccount.length() - 4, bankAccount.length()));
      Glide.with(mActivity)
          .load("file:///android_asset/bank/"
              + "bank_"
              + mUserBankList.getBank().toLowerCase()
              + ".png")
          .apply(new RequestOptions()
              .placeholder(R.drawable.add)
              .error(R.drawable.add)
              .fitCenter())
          .into(imageView);
    }
  }

  @Override public void queryAccOutConditionSuccess(AccOutCondition accOutCondition) {
    String maxAccOutAmount = accOutCondition.getMaxAccOutAmount();
    maxAmount = TextUtils.isEmpty(maxAccOutAmount) ? 0 : Float.valueOf(maxAccOutAmount);
    canOutAmount = accOutCondition.getCanOutAmount();
    etMoney.setHint("最低兑换额度" + accOutCondition.getMinAccOutAmount());
    tvExChangMoney.setText("兑换金额" + canOutAmount + "元");
  }

  @Override public void userAccOutSuccess() {
    AccOutResultFragment fragment =
        new AccOutResultFragment(getString(R.string.acc_out_success));
    startFragment(fragment);
    fragment.setOnConfirmClick(() -> {
      setFragmentResult(RESULTCODE, null);
      popBackStack();
    });
  }

  @Override public void userAccOutFail(String msg) {
    startFragment(new AccOutResultFragment(msg));
  }
}
